require 'MVVM.Sources.View.Adaptor'
--直接绑定Dict,会
BetterListAdaptor = class('BetterListAdaptor', Adaptor)

function BetterListAdaptor:ctor(gameObject, propertyName, prefab, compareFuncs, binder)--这里不管理prefab释放，谁使用这个谁管理prefab的释放
    self.prefab = prefab
    local modifiedCompareFunc = {}
    for _, func in ipairs(compareFuncs) do
        table.insert(modifiedCompareFunc, function(A, B) return func(A:Get_BindingContext(), B:Get_BindingContext()) end)
    end
    self.compareFuncs = modifiedCompareFunc
    self.id2ViewDict = {}
    self.component = gameObject:GetComponent('RectTransform')
    self.autoSort = true
    self:BindProperty(propertyName, binder)
end

function BetterListAdaptor:GetPrefab(viewModel)
    if type(self.prefab) == 'function' then
        return self.prefab(viewModel)
    else
        return self.prefab
    end
end

function BetterListAdaptor:OnViewModelValueChanged(oldValue, newValue)
    newValue = newValue or {}
    --删除没有的View
    for id, view in pairs(self.id2ViewDict) do
        if newValue[id] == nil or self:GetPrefab(newValue[id]) ~= self:GetPrefab(view:Get_BindingContext()) then
            GameObject.Destroy(view.gameObject)
            self.id2ViewDict[id] = nil
        end
    end

    --改变viewModel的
    for id, view in pairs(self.id2ViewDict) do
        if view:Get_BindingContext() ~= newValue[id] then
            view:Set_BindingContext(newValue[id])
        end
    end

    --增加新增的view
    for id, viewModel in pairs(newValue) do
        if self.id2ViewDict[id] == nil then
            local viewGO = GameObject.Instantiate(self:GetPrefab(viewModel))
            viewGO.transform:SetParent(self.component, false)
            local view = GetLuaObject(viewGO)
            view:Set_BindingContext(viewModel)
            self.id2ViewDict[id] = view
        end
    end

    if oldValue ~= nil and not self.autoSort then return end
    self:Sort()
end

function BetterListAdaptor:Sort()
    --排序
    local viewList = {}
    for _, view in pairs(self.id2ViewDict) do
        table.insert(viewList, view)
    end

    if #self.compareFuncs > 0 then
        utils.stableSort(viewList, self.compareFuncs)
    end

    --放置gameObject
    for i = #viewList, 1, -1 do
        local viewTf = viewList[i].transform
        viewTf:SetAsFirstSibling()
        UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(viewTf)
    end
    UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.component)
end